import re
import hashlib
import random

class SIPUtils:
    @staticmethod
    def generate_digest(username, realm, password, method, uri, nonce):
        ha1 = hashlib.md5(f"{username}:{realm}:{password}".encode()).hexdigest()
        ha2 = hashlib.md5(f"{method}:{uri}".encode()).hexdigest()
        return hashlib.md5(f"{ha1}:{nonce}:{ha2}".encode()).hexdigest()
    
    @staticmethod
    def parse_www_authenticate(response):
        for line in response.split('\r\n'):
            if line.startswith("WWW-Authenticate:"):
                auth_line = line[len("WWW-Authenticate:"):].strip()
                return dict(re.findall(r'(\w+)="([^"]+)"', auth_line))
        return None
    
    @staticmethod
    def parse_sip_headers(message):
        headers = {}
        for line in message.split('\r\n'):
            if ':' in line:
                key, value = line.split(':', 1)
                headers[key.strip()] = value.strip()
        return headers
    
    @staticmethod
    def generate_branch():
        return f"z9hG4bK{random.randint(100000, 999999)}"
    
    @staticmethod
    def generate_call_id(local_ip):
        return f"{random.randint(1000000000, 9999999999)}@{local_ip}"
    
    @staticmethod
    def generate_cseq():
        return random.randint(100000, 999999)
    
    @staticmethod
    def generate_tag():
        return str(random.randint(10000, 99999))